from fastapi import Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from fastapi.exceptions import HTTPException
from app.schemas.response import fail
from app.core.logger import logger

# 参数校验失败
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """
    处理请求参数验证异常
    """
    return JSONResponse(
        status_code=200,
        content=fail(msg="请求参数验证失败", code=422)
    )

async def http_exception_handler(request: Request, exc: HTTPException):
    """
    处理HTTP异常
    """
    return JSONResponse(
        status_code=200,
        content=fail(msg=exc.detail, code=exc.status_code)
    )

async def global_exception_handler(request: Request, exc: Exception):
    """
    处理全局异常
    """
    logger.error(f"[global exception] {exc}")
    return JSONResponse(
        status_code=200,
        content=fail(msg="服务器内部错误", code=500)
    )